<?php


namespace app\admin\controller\mall;


use app\admin\model\MallCollage;
use app\admin\model\MallGoods;
use app\admin\model\MallGoodsSpec;
use app\admin\traits\Curd;
use app\common\controller\AdminController;
use EasyAdmin\annotation\ControllerAnnotation;
use EasyAdmin\annotation\NodeAnotation;
use jianyan\excel\Excel;
use think\App;
/**
 * @ControllerAnnotation(title="上传商品")
 */
class UploadGoods extends AdminController
{
    /**
     * 允许修改的字段
     * @var array
     */
    protected $allowModifyFields = [
        'status',
        'sort',
        'remark',
        'is_top',
        'is_novices_exclusive',
        'title',
    ];
    /**
     * 字段排序
     * @var array
     */
    protected $sort = [
        'is_top' => 'desc',
        'sort'   => 'asc',
        'id'     => 'desc',
    ];
    
    public function __construct(App $app)
    {
        parent::__construct($app);
        $this->model = new MallGoods();
    }
    /**
     * @NodeAnotation(title="列表")
     */
    public function staffIndex()
    {
        if ($this->request->isAjax()) {
            if (input('selectFields')) {
                $this->selectWhere = [
                    ['status', '=', 1],
                    ['delete_time', '=', null],
                ];
                return $this->selectList();
            }
            [$page, $limit, $where] = $this->buildTableParames();
            $count = $this->model
                ->where($where)
                ->count();
            $list  = $this->model
                ->where($where)
                ->page($page, $limit)
                ->order($this->sort)
                ->select();
            $data  = [
                'code'  => 0,
                'msg'   => '',
                'count' => $count,
                'data'  => $list,
            ];
            return json($data);
        }
        return $this->fetch();
    }
    /**
     * @NodeAnotation(title="编辑")
     */
    public function edit($id)
    {
        $row = $this->model
            ->with([
                'spec' => function ($query) {
                    $query->where('delete_time', '=', null);
                },
            ])
            ->where('id', $id)
            ->find()->toArray();
//        halt($row);
        empty($row) && $this->error('数据不存在');
        if ($this->request->isPost()) {
            $post = $this->request->post();
            if ($post['collage_num']<1){
                $this->error('拼团人数不能少于1人');
            }
            $rule = [];
            $this->validate($post, $rule);
            try {
                $specAdd = [];
                $spec    = $post[ 'spec' ];
                unset($post[ 'spec' ]);
                unset($post[ 'file' ]);
                foreach ($spec as $key => $value) {
                    $specAdd[] = [
                        'goods_id'    => $id,
                        'name'        => $value,
                        'create_time' => time(),
                        'update_time' => time(),
                    ];
                }
                if (false === MallGoodsSpec::where([['goods_id', '=', $id], ['delete_time', '=', null]])->update(['delete_time' => time()])) {
                    _throwNewException('保存失败');
                }
                if (false === MallGoodsSpec::insertAll($specAdd)) {
                    _throwNewException('保存失败');
                }
                $post[ 'market_price' ]   = $post[ 'market_price' ] * 100;
                $post[ 'discount_price' ] = $post[ 'discount_price' ] * 100;
//                $post[ 'novice_price' ]   = $post[ 'novice_price' ] ?? 0 * 100;
                $post[ 'failure_reward' ] = $post[ 'failure_reward' ] * 100;
                $post[ 'success_reward' ] = $post[ 'success_reward' ] * 100;
                
                $post[ 'update_time' ] = time();
                unset($post[ 'spec' ]);
                $save = $this->model->where('id', $id)->save($post);
            } catch (\Exception $e) {
                $this->error('保存失败');
            }
            $save ? $this->success('保存成功') : $this->error('保存失败');
        }
        $row[ 'market_price' ]   = getPrice($row[ 'market_price' ]);
        $row[ 'discount_price' ] = getPrice($row[ 'discount_price' ]);
        $row[ 'tmall_price' ]    = getPrice($row[ 'tmall_price' ]);
        $row[ 'jd_price' ]       = getPrice($row[ 'jd_price' ]);
        $row[ 'failure_reward' ] = getPrice($row[ 'failure_reward' ]);
        $row[ 'success_reward' ] = getPrice($row[ 'success_reward' ]);
        $row[ 'novice_price' ]   = getPrice($row[ 'novice_price' ]);
        $this->assign('row', $row);
        return $this->fetch();
    }
    /**
     * @NodeAnotation(title="查看")
     */
    public function detail($id)
    {
        $row = $this->model
            ->with([
                'spec' => function ($query) {
                    $query->where('delete_time', '=', null);
                },
            ])
            ->where('id', $id)
            ->find()->toArray();
//        halt($row);
        empty($row) && $this->error('数据不存在');
        $row[ 'market_price' ]   = getPrice($row[ 'market_price' ]);
        $row[ 'discount_price' ] = getPrice($row[ 'discount_price' ]);
        $row[ 'tmall_price' ]    = getPrice($row[ 'tmall_price' ]);
        $row[ 'jd_price' ]       = getPrice($row[ 'jd_price' ]);
        $row[ 'failure_reward' ] = getPrice($row[ 'failure_reward' ]);
        $row[ 'success_reward' ] = getPrice($row[ 'success_reward' ]);
//        $row[ 'novice_price' ]         = getPrice($row[ 'novice_price' ]);
        $row[ 'is_top' ]               = $row[ 'is_top' ] ? '是' : '否';
        $row[ 'is_novices_exclusive' ] = $row[ 'is_novices_exclusive' ] ? '是' : '否';
        $row[ 'images' ]               = explode(',', $row[ 'images' ]);
        $this->assign('row', $row);
        return $this->fetch();
    }
    /**
     * @NodeAnotation(title="添加")
     */
    public function add()
    {
        if ($this->request->isPost()) {
            $post = $this->request->post();
            if ($post['collage_num']<1){
                $this->error('拼团人数不能少于1人');
            }
            $rule = [];
            $this->validate($post, $rule);
            try {
                $specAdd                  = [];
                $spec                     = $post[ 'spec' ];
                $post[ 'market_price' ]   = $post[ 'market_price' ] * 100;
                $post[ 'discount_price' ] = $post[ 'discount_price' ] * 100;
//                $post[ 'novice_price' ]   = $post[ 'novice_price' ] * 100;
                $post[ 'failure_reward' ] = $post[ 'failure_reward' ] * 100;
                $post[ 'success_reward' ] = $post[ 'success_reward' ] * 100;
                $post[ 'create_time' ]    = time();
                $post[ 'update_time' ]    = time();
                unset($post[ 'spec' ]);
                unset($post[ 'file' ]);
                $goodsId = $this->model->insertGetId($post);
                foreach ($spec as $key => $value) {
                    $specAdd[] = [
                        'goods_id'    => $goodsId,
                        'name'        => $value,
                        'create_time' => time(),
                        'update_time' => time(),
                    ];
                }
                if (false === MallGoodsSpec::insertAll($specAdd)) {
                    _throwNewException('保存失败');
                }
            } catch (\Exception $e) {
                $this->error('保存失败:' . $e->getMessage());
            }
            $goodsId ? $this->success('保存成功') : $this->error('保存失败');
        }
        return $this->fetch();
    }
}